package com.situ.web.test;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.web.pojo.Student;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JSONDemo {

    //Java对象转换成JSON字符串
    @Test
    public void test1() throws JsonProcessingException {
        //1.创建Student对象
        Student student = new Student(1, "张三", 23, "男");
        //2.创建Jackson的核心对象ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(student);
        // {"id":1,"name":"张三","age":23,"gender":"男"}
        System.out.println(json);
    }

    @Test
    public void test2() throws JsonProcessingException {
        //1.创建Map
        Map<String, Object> map = new HashMap<>();
        map.put("id", 2);
        map.put("name", "李四");
        map.put("age", 23);
        //2.创建Jackson的核心对象ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(map);
        // {"name":"李四","id":2,"age":23}
        System.out.println(json);
    }

    @Test
    public void test3() throws IOException {
        String json = "{\"id\":1,\"name\":\"张三\",\"age\":23,\"gender\":\"男\"}";
        ObjectMapper objectMapper = new ObjectMapper();
        Student student = objectMapper.readValue(json, Student.class);
        System.out.println(student);
    }
}
